/* Calculator.cpp
Copyright (c) 2008 Michael Zahniser
Please note the license terms (MIT license) at the end of this document.

Function definitions for the Calculator class.
*/

#include "Calculator.h"

#include "Operators.h"
#include "Format.h"

using std::string;
using std::vector;



// Constructor.
Calculator::Calculator()
{
	states.push_back(State());
	state = states.begin();
	
	historyIt = history.end();
}



// Apply the named operation.
void Calculator::operator()(const string &word)
{
	error.clear();
	history.push_back(word);
	historyIt = history.end();
	
	if(word == "^z" || word == "undo")
	{
		if(state != states.begin())
			--state;
		return;
	}
	else if(word == "^y" || word == "redo")
	{
		if(state != states.end() - 1)
			++state;
		return;
	}
	// Duplicate the current state, so a copy stays in the undo history.
	CopyState();
	
	try {
		Do(word);
	}
	catch(string message)
	{
		error = message;
		--state;
		states.pop_back();
	}
}



// Get the size of the stack.
int Calculator::Size() const
{
	return state->Stack().size() + state->Function().size() +
		(state->Mode() == State::PROGRAMMING || !state->Function().empty()) + 
		(state->Mode() == State::DEFINING);
}



// Get the given stack entry, converted to text.
string Calculator::operator[](int index) const
{
	if(state->Mode() == State::DEFINING)
	{
		if(!index)
			return (state->Function().empty() ? "=" : "}");
		--index;
	}
	
	int programSize = state->Function().size();
	if(programSize || state->Mode() == State::PROGRAMMING)
	{
		if(index < programSize)
			return " " + state->Function()[programSize - 1 - index];
		index -= programSize + 1;
		if(index < 0)
			return "{";
	}
	
	int stackSize = state->Stack().size();
	if(index >= stackSize)
		return "?";
	
	return Format::Write(state->Stack()[stackSize - 1 - index], state->Base());
}



// Get the error string from the last operation.
std::string Calculator::Error() const
{
	return error;
}



// Duplicate the current state.
void Calculator::CopyState()
{
	// Clear the redo history; we're doing something new now.
	states.erase(state + 1, states.end());
	// Copy the end of the states.
	states.push_back(states.back());
	state = states.end() - 1;
}



// Get the current state.
State &Calculator::GetState()
{
	return *state;
}



const State &Calculator::GetState() const
{
	return *state;
}



// Retrieve command history.
string Calculator::Previous() const
{
	if(historyIt == history.begin())
		return "";
	--historyIt;
	return *historyIt;
}



string Calculator::Next() const
{
	if(historyIt != history.end())
		++historyIt;
	if(historyIt == history.end())
		return "";
	return *historyIt;
}



// Apply the named operation.
void Calculator::Do(const string &word, int recursion)
{
	if(recursion > 100)
		throw string("recursion too deep");
	
	// If we're not in calculating more, do no interpretation.
	if(state->Mode() != State::CALCULATING)
	{
		state->Push(word);
		return;
	}
	
	// Figure out how to interpret this word.
	Operators &operators = Operators::GetInstance();

	if(state->HasVariable(word))
		state->Push(state->Variable(word));
	else if(state->HasFunction(word))
	{
		vector<string>::const_iterator it = state->Function(word).begin();
		vector<string>::const_iterator end = state->Function(word).end();
		for( ; it != end; ++it)
		{
			if((*it == "ret" || *it == "return") 
					&& state->Mode() != State::SKIPPING)
				break;
			Do(*it, recursion + 1);
		}
	}
	else if(operators.Has(word))
		operators[word](*state);
	else
	{
		double value = Format::Read(word, state->Base());
		if(value == value)
			state->Push(value);
		else
			throw string("value not valid");
	}
}



/* Copyright (c) 2008 Michael Zahniser

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE. */
